package site.marqstree.kotlin.library.base.ui.dialog.update

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentActivity
import com.blankj.utilcode.util.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.subscribeBy
import kotlinx.android.synthetic.main.dialog_apk_update.*
import site.marqstree.kotlin.library.base.data.bean.update.CommonUpdateBean
import site.marqstree.kotlin.library.base.ui.R
import site.marqstree.kotlin.library.base.util.LogUtil
import zlc.season.rxdownload4.download
import zlc.season.rxdownload4.file
import zlc.season.rxdownload4.utils.safeDispose


/*
 * 项目名: KotlinMall
 * 包名: site.marqstree.kotlin.library.base.ui.dialog.update
 * 文件名: DialogUpdate
 * 创建者: marqstree
 * 创建时间: 2020/3/3 10:22
 * 描述: TODO
 */
class DialogUpdate: DialogFragment() {

    private var updateBean: CommonUpdateBean? = null
    private val KEY_UPDATE_BEAN = "UPDATE_BEAN"
    private var disposableDownload: Disposable? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //绑定布局文件
        return inflater.inflate(R.layout.dialog_apk_update,container,false)
    }

    private fun initView(view: View) {
        //设置对话框标题
        tv_update_title.setText(updateBean!!.title)
        //设置对话框内容
        tv_update_content.setText(updateBean!!.content)
        //设置右上角版本名称
        tv_version_name.setText(updateBean!!.versionName)
        //定义升级按钮响应事件函数
        btn_progress.setOnClickListener {
            //不能重复点击“升级”按钮
            btn_progress.isEnabled = false

            disposableDownload = updateBean!!.url
                .download()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeBy(
                    onNext = {progress ->
                        val pc = progress.percent().toInt()
                        btn_progress.progress = pc
                        btn_progress.text = "下载:$pc"
                    },
                    onComplete = {
                        btn_progress.progress = 100
                        btn_progress.text = "下载完成"
                        dismiss()

                        //安装apk
                        val apkFile = updateBean!!.url.file()
                        if(apkFile.exists()) {
                            AppUtils.installApp(apkFile)
                        }
                    },
                    onError = {
                        LogUtil.e("下载升级包失败:${it.message}")
                        btn_progress.text = "重试"
                    }
                )
        }

        btn_update_cancel.setOnClickListener{
            //释放rxDownload下载对象
            disposableDownload?.safeDispose()
            //关闭升级对话框
            dismiss()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //将传入bundle反序列化为实体对象
        //从实体类中获取apk下载url
        //将传入bundle反序列化为实体对象
        //从实体类中获取apk下载url
        updateBean = arguments?.getSerializable(KEY_UPDATE_BEAN) as CommonUpdateBean
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        view?.run{
            initView(view)
        }

        //去除顶部标题
        dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
        //设置背景透明
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    }

    //创建并显示升级对话框
    fun show(
        activity: FragmentActivity,
        bean: CommonUpdateBean
    ) { //通过Bundle，传入apk下载的url
        val bundle = Bundle()
        bundle.putSerializable(
            KEY_UPDATE_BEAN,
            bean
        )
        val dialog = DialogUpdate()
        dialog.setArguments(bundle)
        dialog.show(activity.supportFragmentManager,"UpdateDialog")
    }

}